// 状态管理使用示例
// 展示如何使用新的状态管理架构
import React, { useState } from 'react';
import {
  ErrorBoundary,
  OptimizedList,
  ErrorToast,
} from '@codegraph/editor-core';
import { useOptimizedTabStore } from '../stores/optimizedTabStore';

/**
 * 示例：优化的标签页列表组件
 */
const OptimizedTabList = () => {
  // 使用标准的选择器
  const tabs = useOptimizedTabStore((state) => Array.from(state.tabs.values()));
  const activeTabId = useOptimizedTabStore((state) => state.activeTabId);

  const { setActiveEditor, closeTab } = useOptimizedTabStore();

  const handleTabClick = (tabId: string) => {
    setActiveEditor(tabId);
  };

  return (
    <div className="p-4">
      <h3 className="text-lg font-medium mb-4">Optimized Tab List</h3>
      
      <OptimizedList
        items={tabs}
        keyExtractor={(tab) => tab.id}
        renderItem={(tab, index) => (
          <div
            className={`p-3 border rounded cursor-pointer transition-colors ${
              tab.id === activeTabId
                ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800'
            }`}
            onClick={() => handleTabClick(tab.id)}
          >
            <div className="flex justify-between items-center">
              <div>
                <p className="font-medium">{tab.title}</p>
                <p className="text-sm text-gray-500">{tab.filePath}</p>
                <div className="flex items-center space-x-2 mt-1">
                  <span className={`px-2 py-1 text-xs rounded ${
                    tab.isDirty 
                      ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-200'
                      : 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-200'
                  }`}>
                    {tab.isDirty ? 'Modified' : 'Saved'}
                  </span>
                  <span className="text-xs text-gray-400">
                    {tab.language}
                  </span>
                </div>
              </div>
              
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  closeTab(tab.id);
                }}
                className="px-2 py-1 text-sm bg-red-500 text-white rounded hover:bg-red-600"
              >
                Close
              </button>
            </div>
          </div>
        )}
        virtualized={tabs.length > 20}
        itemHeight={80}
        containerHeight={400}
      />
      
      <div className="mt-4 text-sm text-gray-500">
        Total tabs: {tabs.length} | Active: {activeTabId || 'None'}
      </div>
    </div>
  );
};

/**
 * 示例：防抖搜索组件
 */
const DebouncedSearch: React.FC = () => {
  const [searchResults, setSearchResults] = useState<string[]>([]);
  const [isSearching, setIsSearching] = useState(false);

  // 简化的搜索函数
  const handleSearch = async (query: string) => {
    if (!query.trim()) {
      setSearchResults([]);
      return;
    }

    setIsSearching(true);

    try {
      // 模拟搜索API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      const results = [
        `Result 1 for "${query}"`,
        `Result 2 for "${query}"`,
        `Result 3 for "${query}"`,
      ];
      setSearchResults(results);
    } catch (error) {
      console.error('Search failed:', error);
      setSearchResults([]);
    } finally {
      setIsSearching(false);
    }
  };

  return (
    <div className="p-4">
      <h3 className="text-lg font-medium mb-4">Debounced Search</h3>
      
      <input
        type="text"
        placeholder="Search..."
        onChange={(e) => handleSearch(e.target.value)}
        className="w-full p-2 border border-gray-300 dark:border-gray-600 rounded"
      />
      
      {isSearching && (
        <div className="mt-2 text-sm text-gray-500">Searching...</div>
      )}
      
      <div className="mt-4 space-y-2">
        {searchResults.map((result, index) => (
          <div
            key={index}
            className="p-2 bg-gray-50 dark:bg-gray-800 rounded"
          >
            {result}
          </div>
        ))}
      </div>
    </div>
  );
};

/**
 * 示例：错误处理演示
 */
const ErrorDemo: React.FC = () => {
  const [error, setError] = useState<Error | null>(null);
  const [showToast, setShowToast] = useState(false);

  const triggerError = () => {
    const error = new Error('This is a demo error');
    setError(error);
    setShowToast(true);
  };

  const triggerAsyncError = async () => {
    try {
      // 模拟异步操作失败
      await new Promise((_, reject) => {
        setTimeout(() => reject(new Error('Async operation failed')), 1000);
      });
    } catch (error) {
      setError(error as Error);
      setShowToast(true);
    }
  };

  const triggerComponentError = () => {
    // 这会触发ErrorBoundary
    throw new Error('Component error for testing ErrorBoundary');
  };

  return (
    <div className="p-4">
      <h3 className="text-lg font-medium mb-4">Error Handling Demo</h3>
      
      <div className="space-x-2 mb-4">
        <button
          onClick={triggerError}
          className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
        >
          Trigger Error Toast
        </button>
        
        <button
          onClick={triggerAsyncError}
          className="px-4 py-2 bg-orange-500 text-white rounded hover:bg-orange-600"
        >
          Trigger Async Error
        </button>
        
        <button
          onClick={triggerComponentError}
          className="px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600"
        >
          Trigger Component Error
        </button>
      </div>

      {showToast && error && (
        <ErrorToast
          error={error}
          onClose={() => setShowToast(false)}
          onRetry={() => {
            console.log('Retrying operation...');
            setShowToast(false);
          }}
          severity="high"
        />
      )}
    </div>
  );
};

/**
 * 主示例组件
 */
export const StateManagementExample: React.FC = () => {
  const [showDevTools, setShowDevTools] = useState(false);

  return (
    <ErrorBoundary
      name="StateManagementExample"
      showErrorDetails={true}
      enableAutoRecovery={true}
      onError={(error, errorInfo, errorDetails) => {
        console.log('Error caught by boundary:', { error, errorInfo, errorDetails });
      }}
    >
      <div className="min-h-screen bg-gray-100 dark:bg-gray-900">
        <div className="container mx-auto py-8">
          <h1 className="text-3xl font-bold text-center mb-8">
            State Management Architecture Demo
          </h1>
          
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow">
              <OptimizedTabList />
            </div>
            
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow">
              <DebouncedSearch />
            </div>
            
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow lg:col-span-2">
              <ErrorDemo />
            </div>
          </div>

          <div className="mt-8 text-center">
            <button
              onClick={() => setShowDevTools(!showDevTools)}
              className="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
            >
              {showDevTools ? 'Hide' : 'Show'} DevTools Panel
            </button>
          </div>

          <div className="mt-4 text-center text-sm text-gray-500">
            <p>
              This demo showcases the new state management architecture with:
            </p>
            <ul className="mt-2 space-y-1">
              <li>✅ Modular Zustand store architecture</li>
              <li>✅ Performance optimizations (batching, debouncing, memoization)</li>
              <li>✅ State persistence with migration support</li>
              <li>✅ Comprehensive error handling and recovery</li>
              <li>✅ Redux DevTools integration</li>
              <li>✅ Optimized React components</li>
            </ul>
          </div>
        </div>

        {/* DevTools功能暂时不可用 */}
        {showDevTools && (
          <div className="mt-4 p-4 bg-gray-100 dark:bg-gray-800 rounded">
            <p>DevTools面板功能正在开发中...</p>
          </div>
        )}
      </div>
    </ErrorBoundary>
  );
};

export default StateManagementExample;
